package com.kly.user.serviceImpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.StringUtils;
import com.google.api.client.util.Lists;
import com.google.common.collect.Maps;
import com.kly.user.db.dao.UserWlmDao;
import com.kly.user.db.dbo.UserConversationDBO;
import com.kly.user.db.entity.UserWlmEntity;
import com.kly.user.dto.UserConversationVO;
import com.kly.user.enums.AppsFlyerEventDefType;
import com.kly.user.service.AppsflyerService;
import com.kly.user.db.dao.UserConversationDao;
import com.kly.user.db.dao.UserConversationRecordDao;
import com.kly.user.db.entity.UserConversationEntity;
import com.kly.user.db.entity.UserConversationRecordEntity;
import com.kly.user.dto.UserConversationDto;
import com.kly.user.dto.UserConversationRecordDto;
import com.kly.user.enums.ConversationType;
import com.kly.user.service.UserConversationService;
import com.kly.user.utils.ServiceUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service("userConversationService")
public class UserConversationServiceImpl implements UserConversationService {
    @Resource
    UserConversationRecordDao userConversationRecordDao;

    @Resource
    UserConversationDao userConversationDao;
    @Resource
    AppsflyerService appsflyerService;
    @Resource
    UserWlmDao userWlmDao;

    @Override
    public void addUserConversationList(List<UserConversationRecordDto> userRecordList) {
        for (UserConversationRecordDto userRecord : userRecordList) {
            addUserConversation(userRecord);

            // 推送注册数据到appsFlyer
//            pushDataToAppsFlyer(userRecord.getUserCode(), userRecord.getToUserCode(), userRecord.getConversationsType());

        }
    }

    @Override
    public void addUserConversation(UserConversationRecordDto userConversationRecordDto) {
        UserConversationRecordEntity entity = new UserConversationRecordEntity();
        BeanUtil.copyProperties(userConversationRecordDto, entity);

        List<UserConversationRecordEntity> userConversationList = getUserConversationRecordEntities(userConversationRecordDto);

        if (CollUtil.isNotEmpty(userConversationList)) {
            UserConversationRecordEntity recordEntity = userConversationList.get(0);
            recordEntity.setConversationsNumber(userConversationRecordDto.getConversationsNumber());
            userConversationRecordDao.updateByPrimaryKey(recordEntity);
        } else {
            pushDataToAppsFlyer(entity.getUserCode(), entity.getToUserCode(), entity.getConversationsType());
            userConversationRecordDao.insert(entity);
        }

    }

    private List<UserConversationRecordEntity> getUserConversationRecordEntities(UserConversationRecordDto userConversationRecordDto) {
        Map<String, Object> params = ServiceUtils.getParams();
        params.put("userCode", userConversationRecordDto.getUserCode());
        params.put("toUserCode", userConversationRecordDto.getToUserCode());
        params.put("conversationsType", userConversationRecordDto.getConversationsType());
        return userConversationRecordDao.selectByParams(params);
    }

    private void pushDataToAppsFlyer(String userCode, String toUserCode, Integer conversationsType) {
        final HashMap<String, Object> pushData = Maps.newHashMap();
        pushData.put("userCode", userCode);
        pushData.put("toUserCode", toUserCode);
        if (ConversationType.EFFECTIVE_CONVERSATIONS.getCode() == conversationsType) {
            appsflyerService.asyncTraceEvent(AppsFlyerEventDefType.Active_Chat, pushData);
        }
        if (ConversationType.DEEP_CONVERSATIONS.getCode() == conversationsType) {
            appsflyerService.asyncTraceEvent(AppsFlyerEventDefType.Deep_Chat, pushData);
        }
    }


    @Override
    public UserConversationDto getUserConversation(String userCode, String toUserCode) {
        Map<String, Object> params = ServiceUtils.getParams();
        params.put("userCode", userCode);
        params.put("userCodeFriend", toUserCode);
        List<UserConversationEntity> userConversationEntities = userConversationDao.selectByParams(params);
        if (CollUtil.isNotEmpty(userConversationEntities)) {
            UserConversationDto userConversationDto = new UserConversationDto();
            BeanUtil.copyProperties(userConversationEntities.get(0), userConversationDto);
            return userConversationDto;
        }
        return null;
    }


    @Override
    public Map<Integer, List<UserConversationRecordDto>> getUserConversationList(Map<String, Object> params) {
        List<UserConversationRecordEntity> userConversationList = userConversationRecordDao.getUserConversationList(params);
        if (CollUtil.isNotEmpty(userConversationList)) {
            return userConversationList.stream()
                    .map(userConversation -> {
                        UserConversationRecordDto userRecordDto = new UserConversationRecordDto();
                        BeanUtil.copyProperties(userConversation, userRecordDto);
                        return userRecordDto;
                    })
                    .collect(Collectors.groupingBy(UserConversationRecordDto::getConversationsType, Collectors.toList()));
        }
        return new HashMap<>();
    }

    /**
     * 查询用户会话中发送消息数量
     */
    @Override
    public Map<String, UserConversationRecordDto> getUserConversationMsgNum(Map<String, Object> params) {
        List<UserConversationRecordEntity> userConversationList =
                userConversationRecordDao.getUserConversationMsgNum(params);
        if (CollUtil.isNotEmpty(userConversationList)) {
            return userConversationList.stream().collect(Collectors.toMap(UserConversationRecordEntity::getUserCode,
                    userConversation -> {
                        UserConversationRecordDto userRecordDto = new UserConversationRecordDto();
                        BeanUtil.copyProperties(userConversation, userRecordDto);
                        return userRecordDto;
                    }));
        }
        return new HashMap<>();
    }

    @Override
    public Response isExists(String fromUserCode, String toUserCode, Integer conversationType) {
        final UserConversationRecordEntity userConversation = userConversationRecordDao.getUserConversation(fromUserCode, toUserCode, conversationType);
        return Response.ok(Objects.nonNull(userConversation));
    }


    @Override
    public Response<List<UserConversationVO>> getAllConversationByUserCode(String userCode) {
        if (StringUtils.isEmpty(userCode)) {
            return Response.ok(Lists.newArrayList());
        }
        final List<UserConversationDBO> userConversationEntityList = userConversationDao.queryAllConversionByUserCode(userCode);
        if (CollectionUtils.isEmpty(userConversationEntityList)) {
            return Response.ok(Lists.newArrayList());
        }

        // 获取用户通过flashchat建联记录
        final List<UserWlmEntity> connectRecords = userWlmDao.queryFlashchatRecords(userCode);

        final List<UserConversationVO> conversationVOS = userConversationEntityList.parallelStream().map(o -> {
            UserConversationVO vo = new UserConversationVO();
            BeanUtils.copyProperties(o, vo);
            if (isExistsFlashChat(connectRecords, o)) {
                vo.setFlashchatFlag(1);
            } else {
                vo.setFlashchatFlag(0);
            }
            return vo;
        }).collect(Collectors.toList());
        return Response.ok(conversationVOS);
    }

    private boolean isExistsFlashChat(List<UserWlmEntity> connectRecords, UserConversationDBO o) {
        if (CollectionUtils.isEmpty(connectRecords)) {
            return Boolean.FALSE;
        }
        return connectRecords.parallelStream().anyMatch(wlm -> {
            if (wlm.getUserCode().equals(o.getUserCode()) && wlm.getUserCodeWlm().equals(o.getUserCodeFriend())) {
                return Boolean.TRUE;
            }
            if (wlm.getUserCodeWlm().equals(o.getUserCode()) && wlm.getUserCode().equals(o.getUserCodeFriend())) {
                return Boolean.TRUE;
            }
            return Boolean.FALSE;
        });
    }
}
